package com.suse.lhw.hms.foodserver.config.tools;

import java.lang.reflect.Field;

/**
 * @ProjectName: health_manage_system
 * @Package: com.suse.lhw.hms.foodserver.config.tools
 * @ClassName: updateTool
 * @Description: java类作用描述
 * @Author: 李鸿炜
 * @CreateDate: 2020/4/26 17:08
 * @UpdateUser: 更新者
 * @UpdateDate: 2020/4/26 17:08
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class updateTool {
    /**
     * @Author:Hongwei Li
     * @Description:更新类，如果前端传过来的类有空值，则不更新该属性，做法是通过反射将原有类的 的属性一一set为新类的非空属性
     * @Date:17:09 2020/4/26
     * @Param:
     * @Return:
     **/
    public static Object updateBean(Object src, Object desc) throws Exception {
        Class<?> srcClass = src.getClass();
        Class<?> descClass = desc.getClass();
        if (!descClass.equals(srcClass)) {
            throw new Exception("源对象与目标对象类型不一致！");
        }

        Field[] srcClassFields = srcClass.getDeclaredFields();
        Field[] descClassFields = descClass.getDeclaredFields();

        for (int i = 0; i < descClassFields.length; i++) {
            descClassFields[i].setAccessible(true);
            Object o = descClassFields[i].get(desc);
            if (o != null && !"".equals(o.toString().trim())) {
                srcClassFields[i].setAccessible(true);
                srcClassFields[i].set(src, o);
            }
        }

        return src;

    }
}
